// Copilot Bridge Panel JavaScript

(function() {
    'use strict';

    // VS Code API
    const vscode = acquireVsCodeApi();
    
    // 状态管理
    let currentState = {
        selectedRange: null,
        editorInfo: null,
        history: [],
        references: {
            files: new Set(),
            symbols: new Set()
        },
        autocompleteVisible: false,
        autocompleteItems: [],
        selectedAutocompleteIndex: -1,
        isUpdatingReferences: false
    };

    // DOM 元素
    const elements = {
        // 智能提示输入
        promptInput: document.getElementById('promptInput'),
        autocompleteDropdown: document.getElementById('autocompleteDropdown'),
        referenceTags: document.getElementById('referenceTags'),

        // 操作按钮
        generateBtn: document.getElementById('generateBtn'),

        // 历史记录
        historyHeader: document.getElementById('historyHeader'),
        historyContent: document.getElementById('historyContent'),
        historyList: document.getElementById('historyList'),
        collapseBtn: document.getElementById('collapseBtn'),

        // 消息容器
        messageContainer: document.getElementById('messageContainer')
    };

    // 初始化
    function init() {
        setupEventListeners();
        // 通知扩展 webview 已准备就绪
        vscode.postMessage({ type: 'ready' });
    }

    // 设置事件监听器
    function setupEventListeners() {
        // 生成按钮
        elements.generateBtn.addEventListener('click', generateContext);

        // 历史记录折叠按钮
        elements.collapseBtn.addEventListener('click', toggleHistoryCollapse);
        

        
        // 智能提示输入框事件
        elements.promptInput.addEventListener('input', handlePromptInput);
        elements.promptInput.addEventListener('keydown', handlePromptKeydown);
        elements.promptInput.addEventListener('blur', handlePromptBlur);
        elements.promptInput.addEventListener('blur', hideAutocomplete);
        
        // 键盘快捷键
        document.addEventListener('keydown', (e) => {
            if (e.ctrlKey && e.key === 'Enter') {
                e.preventDefault();
                generateContext();
            }
        });
    }

    // 生成上下文
    function generateContext() {
        const prompt = elements.promptInput.value.trim();

        // 收集引用信息
        const fileReferences = Array.from(currentState.references.files);
        const symbolReferences = Array.from(currentState.references.symbols);

        // 发送消息到扩展
        vscode.postMessage({
            type: 'generateContext',
            data: {
                prompt,
                fileReferences,
                symbolReferences
            }
        });
    }

    // 切换历史记录折叠状态
    function toggleHistoryCollapse() {
        const content = elements.historyContent;
        const btn = elements.collapseBtn;
        const isCollapsed = content.classList.contains('collapsed');

        if (isCollapsed) {
            content.classList.remove('collapsed');
            btn.classList.remove('collapsed');
        } else {
            content.classList.add('collapsed');
            btn.classList.add('collapsed');
        }
    }

    // 处理输入框失焦
    function handlePromptBlur() {
        // 延迟处理，避免与点击自动完成项冲突
        setTimeout(() => {
            hideAutocomplete();
        }, 150);
    }

    // 解析输入文本中的引用
    function parseReferences(text) {
        const fileRefs = [];
        const symbolRefs = [];

        // 解析文件引用 @filename
        const fileMatches = text.match(/@([^\s@#]+)/g);
        if (fileMatches) {
            fileMatches.forEach(match => {
                const filename = match.substring(1);
                if (!fileRefs.includes(filename)) {
                    fileRefs.push(filename);
                }
            });
        }

        // 解析符号引用 #symbol
        const symbolMatches = text.match(/#([^\s@#]+)/g);
        if (symbolMatches) {
            symbolMatches.forEach(match => {
                const symbol = match.substring(1);
                if (!symbolRefs.includes(symbol)) {
                    symbolRefs.push(symbol);
                }
            });
        }

        return { files: fileRefs, symbols: symbolRefs };
    }



    // 创建引用标签
    function createReferenceTag(name, type) {
        const tag = document.createElement('div');
        tag.className = `reference-tag ${type}-ref`;

        const icon = document.createElement('span');
        icon.className = 'reference-tag-icon';

        const text = document.createElement('span');
        text.className = 'reference-tag-text';
        text.textContent = name;

        const close = document.createElement('span');
        close.className = 'reference-tag-close';
        close.textContent = '×';
        close.addEventListener('click', (e) => {
            e.stopPropagation();
            removeReference(name, type);
        });

        tag.appendChild(icon);
        tag.appendChild(text);
        tag.appendChild(close);

        // 点击标签定位到输入框中的引用
        tag.addEventListener('click', () => {
            const prefix = type === 'file' ? '@' : '#';
            const searchText = prefix + name;
            const inputValue = elements.promptInput.value;
            const index = inputValue.indexOf(searchText);

            if (index !== -1) {
                elements.promptInput.focus();
                elements.promptInput.setSelectionRange(index, index + searchText.length);
            }
        });

        return tag;
    }

    // 移除引用
    function removeReference(name, type) {
        // 从状态中移除引用
        if (type === 'file') {
            currentState.references.files.delete(name);
        } else {
            currentState.references.symbols.delete(name);
        }

        // 重新渲染标签
        renderReferenceTags();
    }

    // 渲染引用标签（不触发文本更新）
    function renderReferenceTags() {
        elements.referenceTags.innerHTML = '';

        // 添加文件引用标签
        currentState.references.files.forEach(filename => {
            const tag = createReferenceTag(filename, 'file');
            elements.referenceTags.appendChild(tag);
        });

        // 添加符号引用标签
        currentState.references.symbols.forEach(symbol => {
            const tag = createReferenceTag(symbol, 'symbol');
            elements.referenceTags.appendChild(tag);
        });
    }

    // 处理智能提示输入
    function handlePromptInput(e) {
        const value = e.target.value;
        const cursorPos = e.target.selectionStart;

        // 检查是否输入了 @ 或 # 符号
        const beforeCursor = value.substring(0, cursorPos);
        const atMatch = beforeCursor.match(/@(\w*)$/);
        const hashMatch = beforeCursor.match(/#(\w*)$/);

        if (atMatch) {
            // 显示文件列表
            showAutocomplete('file', atMatch[1]);
        } else if (hashMatch) {
            // 显示符号列表
            showAutocomplete('symbol', hashMatch[1]);
        } else {
            hideAutocomplete();
        }
    }

    // 处理键盘事件
    function handlePromptKeydown(e) {
        if (currentState.autocompleteVisible) {
            switch (e.key) {
                case 'ArrowDown':
                    e.preventDefault();
                    navigateAutocomplete(1);
                    break;
                case 'ArrowUp':
                    e.preventDefault();
                    navigateAutocomplete(-1);
                    break;
                case 'Enter':
                    e.preventDefault();
                    selectAutocompleteItem();
                    break;
                case 'Escape':
                    e.preventDefault();
                    hideAutocomplete();
                    break;
            }
        } else if (e.ctrlKey && e.key === 'Enter') {
            e.preventDefault();
            generateContext();
        }
    }

    // 显示自动完成
    function showAutocomplete(type, query) {
        currentState.autocompleteVisible = true;
        currentState.selectedAutocompleteIndex = -1;

        // 计算下拉框位置
        positionAutocompleteDropdown();

        if (type === 'file') {
            // 获取已引用的文件列表，避免重复引用
            const excludeFiles = Array.from(currentState.references.files);
            vscode.postMessage({
                type: 'getFileList',
                data: {
                    query,
                    excludeFiles
                }
            });
        } else if (type === 'symbol') {
            vscode.postMessage({
                type: 'getSymbolList',
                data: { query }
            });
        }
    }

    // 计算并设置自动完成下拉框的位置
    function positionAutocompleteDropdown() {
        const input = elements.promptInput;
        const dropdown = elements.autocompleteDropdown;

        // 获取光标位置
        const cursorPos = input.selectionStart;
        const textBeforeCursor = input.value.substring(0, cursorPos);

        // 获取输入框的位置
        const inputRect = input.getBoundingClientRect();

        // 计算光标在输入框中的相对位置
        const lines = textBeforeCursor.split('\n');
        const currentLine = lines.length - 1;
        const currentColumn = lines[lines.length - 1].length;

        // 估算光标位置
        const lineHeight = parseInt(window.getComputedStyle(input).lineHeight) || 20;
        const charWidth = 8; // 大概的字符宽度

        const cursorX = inputRect.left + 16 + (currentColumn * charWidth); // 16 是 padding
        const cursorY = inputRect.top + 40 + (currentLine * lineHeight); // 40 是上方 padding

        // 设置下拉框位置，确保不超出视口
        dropdown.style.left = Math.min(cursorX, window.innerWidth - 220) + 'px';
        dropdown.style.top = (cursorY + lineHeight + 2) + 'px';
    }

    // 隐藏自动完成
    function hideAutocomplete() {
        currentState.autocompleteVisible = false;
        elements.autocompleteDropdown.style.display = 'none';
    }

    // 导航自动完成列表
    function navigateAutocomplete(direction) {
        const maxIndex = currentState.autocompleteItems.length - 1;
        currentState.selectedAutocompleteIndex += direction;

        if (currentState.selectedAutocompleteIndex < 0) {
            currentState.selectedAutocompleteIndex = maxIndex;
        } else if (currentState.selectedAutocompleteIndex > maxIndex) {
            currentState.selectedAutocompleteIndex = 0;
        }

        updateAutocompleteSelection();
    }

    // 更新自动完成选择
    function updateAutocompleteSelection() {
        const items = elements.autocompleteDropdown.querySelectorAll('.autocomplete-item');
        items.forEach((item, index) => {
            item.classList.toggle('selected', index === currentState.selectedAutocompleteIndex);
        });
    }

    // 选择自动完成项
    function selectAutocompleteItem() {
        if (currentState.selectedAutocompleteIndex >= 0 &&
            currentState.selectedAutocompleteIndex < currentState.autocompleteItems.length) {
            const item = currentState.autocompleteItems[currentState.selectedAutocompleteIndex];
            insertReference(item);
        }
    }

    // 插入引用
    function insertReference(item) {
        const input = elements.promptInput;
        const value = input.value;
        const cursorPos = input.selectionStart;

        // 找到要替换的部分
        const beforeCursor = value.substring(0, cursorPos);
        const afterCursor = value.substring(cursorPos);

        let replaceMatch;

        if (item.type === 'file') {
            replaceMatch = beforeCursor.match(/@(\w*)$/);
        } else if (item.type === 'symbol') {
            replaceMatch = beforeCursor.match(/#(\w*)$/);
        }

        if (replaceMatch) {
            // 移除输入框中的 @ 或 # 符号和部分输入
            const newValue = beforeCursor.substring(0, beforeCursor.length - replaceMatch[0].length) + afterCursor;
            input.value = newValue;

            // 设置光标位置
            const newCursorPos = cursorPos - replaceMatch[0].length;
            input.setSelectionRange(newCursorPos, newCursorPos);

            // 添加到引用状态
            if (item.type === 'file') {
                currentState.references.files.add(item.name);
            } else {
                currentState.references.symbols.add(item.name);
            }

            // 重新渲染标签
            renderReferenceTags();
        }

        hideAutocomplete();
        input.focus();
    }

    // 更新历史记录
    function updateHistory(history) {
        currentState.history = history;
        
        if (history.length === 0) {
            elements.historyList.innerHTML = '<div class="history-placeholder">暂无历史记录</div>';
            return;
        }
        
        const historyHtml = history.map((item, index) => {
            const date = new Date(item.timestamp);
            const timeStr = date.toLocaleString('zh-CN', {
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit'
            });
            
            // 构建引用信息显示
            let referencesInfo = '';
            if (item.fileReferences && item.fileReferences.length > 0) {
                referencesInfo += `📄 ${item.fileReferences.length}个文件`;
            }
            if (item.symbolReferences && item.symbolReferences.length > 0) {
                if (referencesInfo) referencesInfo += ' ';
                referencesInfo += `# ${item.symbolReferences.length}个符号`;
            }
            if (referencesInfo) {
                referencesInfo = ` (${referencesInfo})`;
            }

            return `
                <div class="history-item" data-index="${index}">
                    <div class="history-header">
                        <span class="history-title">${item.fileName} - ${item.rangeType === 'file' ? '整个文件' : item.rangeType === 'selection' ? '选中文本' : item.rangeType === 'multi-file' ? '多文件' : '可见区域'}${referencesInfo}</span>
                        <span class="history-time">${timeStr}</span>
                    </div>
                    <div class="history-preview">${item.prompt || '无提示'}</div>
                </div>
            `;
        }).join('');
        
        elements.historyList.innerHTML = historyHtml;
        
        // 添加点击事件
        elements.historyList.querySelectorAll('.history-item').forEach(item => {
            item.addEventListener('click', () => {
                const index = parseInt(item.getAttribute('data-index'));
                loadHistoryItem(index);
            });
        });
    }

    // 加载历史记录项
    function loadHistoryItem(index) {
        vscode.postMessage({
            type: 'loadHistoryItem',
            data: { index }
        });
    }

    // 加载历史记录项到界面
    function loadHistoryItemToUI(item) {
        // 清空当前引用状态
        currentState.references.files.clear();
        currentState.references.symbols.clear();

        // 设置输入框文本
        elements.promptInput.value = item.prompt || '';

        // 优先使用保存的引用信息，如果没有则解析文本
        if (item.fileReferences && item.symbolReferences) {
            // 使用保存的引用信息
            item.fileReferences.forEach(file => currentState.references.files.add(file));
            item.symbolReferences.forEach(symbol => currentState.references.symbols.add(symbol));
        } else {
            // 兼容旧版本：解析文本中的引用
            const refs = parseReferences(item.prompt || '');
            refs.files.forEach(file => currentState.references.files.add(file));
            refs.symbols.forEach(symbol => currentState.references.symbols.add(symbol));
        }

        // 渲染引用标签
        renderReferenceTags();

        showMessage('success', `已加载历史记录: ${item.fileName}`);
    }

    // 显示消息
    function showMessage(type, message) {
        const messageEl = document.createElement('div');
        messageEl.className = `message ${type}`;
        messageEl.textContent = message;
        
        elements.messageContainer.appendChild(messageEl);
        
        // 3秒后自动移除
        setTimeout(() => {
            if (messageEl.parentNode) {
                messageEl.parentNode.removeChild(messageEl);
            }
        }, 3000);
    }

    // 处理来自扩展的消息
    window.addEventListener('message', event => {
        const message = event.data;

        switch (message.type) {
            case 'updateHistory':
                updateHistory(message.data);
                break;
            case 'loadHistoryItem':
                loadHistoryItemToUI(message.data);
                break;
            case 'showMessage':
                showMessage(message.data.type, message.data.message);
                break;
            case 'fileList':
                displayAutocomplete(message.data, 'file');
                break;
            case 'symbolList':
                displayAutocomplete(message.data, 'symbol');
                break;
        }
    });

    // 显示自动完成列表
    function displayAutocomplete(items, type) {
        if (!currentState.autocompleteVisible) return;

        currentState.autocompleteItems = items.map(item => ({
            ...item,
            type: type
        }));

        if (items.length === 0) {
            hideAutocomplete();
            return;
        }

        const html = items.map((item, index) => {
            let icon, name, detail, activeIndicator = '';

            if (type === 'file') {
                icon = '📄';
                name = item.name;
                detail = item.path;
                // 为当前打开的文件添加特殊标识
                if (item.isActive) {
                    activeIndicator = '<span class="active-file-indicator">●</span>';
                    detail = `${detail} (当前打开)`;
                }
            } else if (type === 'symbol') {
                icon = getSymbolIcon(item.kind);
                name = item.name;
                detail = item.kind;
            }

            return `
                <div class="autocomplete-item ${item.isActive ? 'active-file' : ''}" data-index="${index}">
                    <span class="autocomplete-icon">${icon}</span>
                    <span class="autocomplete-name">${name}</span>
                    ${activeIndicator}
                    <span class="autocomplete-detail">${detail}</span>
                </div>
            `;
        }).join('');

        elements.autocompleteDropdown.innerHTML = html;
        elements.autocompleteDropdown.style.display = 'block';

        // 添加点击事件
        elements.autocompleteDropdown.querySelectorAll('.autocomplete-item').forEach((item, index) => {
            item.addEventListener('mousedown', (e) => {
                e.preventDefault(); // 防止失去焦点
                currentState.selectedAutocompleteIndex = index;
                selectAutocompleteItem();
            });
        });

        currentState.selectedAutocompleteIndex = 0;
        updateAutocompleteSelection();
    }

    // 获取符号图标
    function getSymbolIcon(kind) {
        const icons = {
            'Function': '🔧',
            'Method': '🔧',
            'Class': '📦',
            'Interface': '📋',
            'Variable': '📊',
            'Constant': '🔒',
            'Property': '🏷️',
            'Field': '🏷️',
            'Constructor': '🏗️',
            'Enum': '📝',
            'Module': '📁',
            'Namespace': '📁'
        };
        return icons[kind] || '🔧';
    }

    // 页面加载完成后初始化
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }

})();
